package com.example.storage;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class recipe extends AppCompatActivity {

    private static final String BASE_URL = "http://apis.juhe.cn/fapigx/caipu/query";
    private static final String APP_KEY = "2faaa600c4c11253aef96eb92ad3b20f";

    private EditText etFoodName;
    private Button btnSearch;
    private RecyclerView rvResults;
    private RecipeAdapter recipeAdapter;
    private List<RecipeResponse.Result.Recipe> recipeList = new ArrayList<>();
    private OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe);

        etFoodName = findViewById(R.id.etFoodName);
        btnSearch = findViewById(R.id.btnSearch);
        rvResults = findViewById(R.id.rvResults);

        client = new OkHttpClient();

        rvResults.setLayoutManager(new LinearLayoutManager(this));
        recipeAdapter = new RecipeAdapter(recipeList);
        rvResults.setAdapter(recipeAdapter);

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchRecipes();
            }
        });
    }

    private void searchRecipes() {
        String foodName = etFoodName.getText().toString();
        String url = BASE_URL + "?key=" + APP_KEY + "&word=" + foodName;

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(recipe.this, "请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    parseJSONWithJSONObject(responseData);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(recipe.this, "请求失败: " + response.message(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void parseJSONWithJSONObject(String jsonData) {
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            int errorCode = jsonObject.getInt("error_code");
            if (errorCode == 0) {
                JSONObject result = jsonObject.getJSONObject("result");
                JSONArray list = result.getJSONArray("list");
                final List<RecipeResponse.Result.Recipe> recipes = new ArrayList<>();
                for (int i = 0; i < list.length(); i++) {
                    JSONObject recipe = list.getJSONObject(i);
                    String cpName = recipe.getString("cp_name");
                    String zuofa = recipe.getString("zuofa");
                    RecipeResponse.Result.Recipe recipeObj = new RecipeResponse.Result.Recipe();
                    recipeObj.setCpName(cpName);
                    recipeObj.setZuofa(zuofa);
                    recipes.add(recipeObj);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        recipeList.clear();
                        recipeList.addAll(recipes);
                        recipeAdapter.notifyDataSetChanged();
                    }
                });
            } else {
                final String reason = jsonObject.getString("reason");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(recipe.this, "请求失败: " + reason, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } catch (JSONException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(recipe.this, "解析失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}
